<?php
/**
 * 
 * 
 *
 */
class Quad_Db_Adapter_Mysqli extends Quad_Db_Adapter_Abstract {
	
	public function connect() {
		if (!$this->_conn) {
      $this->_conn = new mysqli(
        $this->_db->hostname, $this->_db->username, $this->_db->password,
        $this->_db->database, $this->_db->port, $this->_db->socket
      );
      if ($this->_conn->connect_error) {
      	throw new Exception($this->_conn->connect_error);
      }
		}
		return $this->_conn;
	}
	
	public function getStmt($sql, $values) {
		self::$_bind = $values;
		self::$_orderedTypes = '';
		self::$_ordered = array();
		$qmarked = preg_replace_callback('/\:[\w_]+/', array('self', '_bind'));
		$stmt = $this->_conn->prepare($qmarked);
		if (count(self::$_ordered)) {
			$args = array_merge(array(self::$_orderedTypes), self::$_ordered);
			self::$_bind = self::$_orderedTypes = self::$_ordered = null;
			call_user_func_array(array($stmt, 'bind_param'), $args);
			
		} else {
			$stmt = $this->_conn->prepare($sql);
		}
		return $stmt;
	}
	
	public function _bind($match) {
		$field = substr($match, 1);
		self::$_orderedTypes .= self::_getBindType(self::$_bind[$field]);
		self::$_ordered .= self::$_bind[$field];
		return '?';
	}
	
	public function _getBindType($val) {
		if ($val instanceof Quad_Db_Blob) {
			return 'b';
			
		} elseif ($val instanceof Quad_Db_Clob) {
			return 's';
			
		} elseif ((string)(float) $val == (string) $val) {
			return 'd';
			
		} elseif ((string)(int) $val == (string) $val) {
			return 'i';
			
		} else {
			return 's';
		}
	}
	
	public static function quote($objectName) {
		return "`$objectName`";
	}
	
	public static function escape($value) {
		$this->_conn->real_escape_string($value);
	}
   
}